import { defineStore } from "pinia";
import { computed, ref } from "vue";
import store from "store2";
import _ from "lodash";
const WEBSITE_LIST = "websiteList";

const useWebsiteStore = defineStore("website", () => {
    const websiteListRef = ref(store.get(WEBSITE_LIST) || []);
    const websites = computed(() => {
        return (keyword) => {
            if (keyword === "") {
                return websiteListRef.value
            } else {
                return _.filter(websiteListRef.value, (item) => {
                    const partten = new RegExp(keyword, "i");
                    return partten.test(item.title);
                })
            }
        }
    });
    /** 添加数据 */
    const addWebsite = (websiteInfo) => {
        if (_.find(websiteListRef.value, { url: websiteInfo.url })) {
            CONTEXTAPI.alert("此网址已被添加");
        } else {
            websiteListRef.value.unshift(websiteInfo);
            store(WEBSITE_LIST, websiteListRef.value);
        }

    };
    /** 删除数据 */
    const deleteWebsite = (url) => {
        websiteListRef.value = websiteListRef.value.filter(websiteItem => websiteItem.url !== url);
        // websiteListRef.value = _.dropWhile(websiteListRef.value, { url });
        store(WEBSITE_LIST, websiteListRef.value);
    }
    return {
        websites,
        websiteList: websiteListRef,
        addWebsite,
        deleteWebsite
    };
});

export default useWebsiteStore;